import UUID from 'uuid-js';
import Collection from './collection';

export default class Client {
  constructor(url) {
    if (!window.WebSocket) {
      throw new Error('客户端不支持websocket');
    }

    const clientId = UUID.create().toString();
    this.id = clientId;
    this.isOpen = false;
    this.websocket = new WebSocket(url);
    this.websocket.onopen = () => {
      console.log('connect open');
      this.isOpen = true;
      this.waitingOpenSendList.forEach(msg => {
        this.send(msg);
      });
    };
    this.websocket.onmessage = event => {
      console.log('数据已接收...', event);
      const { data } = event;
      const dataObj = JSON.parse(data);
      if (dataObj.from === clientId) {
        console.log(
          '本机发出，不处理',
          dataObj.from,
          clientId,
          dataObj.from === clientId
        );
        return false;
      }

      console.log(this.subscribes, dataObj);
      if (this.subscribes[dataObj.name]) {
        this.subscribes[dataObj.name].action(dataObj);
      }

      return false;
    };

    // 订阅列表
    this.subscribes = {};

    // 等待open后的send列表
    this.waitingOpenSendList = [];
  }

  // 订阅
  subscribe(name) {
    if (!this.subscribes[name]) {
      // 向服务端发送订阅请求
      this.send({
        name,
        clientId: this.id,
        type: 'subscribe'
      });

      this.subscribes[name] = new Collection(name);
      // 增加对change事件的监听
      this.subscribes[name].addChange(event => {
        console.log('change', event);
        this.send({
          name,
          type: 'change',
          clientId: this.id,
          data: event
        });
      });
    }

    return this.subscribes[name];
  }

  send(obj) {
    console.log('send', this.isOpen, obj);
    if (this.isOpen) {
      this.websocket.send(JSON.stringify(obj));
    } else {
      this.waitingOpenSendList.push(obj);
    }
  }

  close() {
    this.websocket.close();
  }
}
